﻿Imports System.Net
Imports System.Net.Sockets

Friend Class Listener
    Private Shared mListenThread As System.Threading.Thread
    Private Shared mListener As TcpListener


    Public ReadOnly Property CurrentPort() As Integer
        Get
            Return CType(mListener.LocalEndpoint, IPEndPoint).Port
        End Get
    End Property

    Public Sub Start()
        mListenThread = New System.Threading.Thread(AddressOf Listener)
        mListenThread.Name = "TCP Listening Thread"
        mListenThread.IsBackground = True
        mListenThread.Start()
    End Sub
    Public Sub [Stop](ByVal message As Framework.Message)
        message.SetMessage("Shutting down TCP/IP server...")
        mListener.Stop()
        mListenThread.Abort()
        mListenThread.Join(10000)
    End Sub

    Private Shared Sub Listener()
        Try
            mListener = New TcpListener(IPAddress.Any, Settings.Port)
            mListener.Start()
            Do
                Try
                    If mListener.Pending Then
                        Dim clsNewClient As TcpClient = mListener.AcceptTcpClient
                        Dim clsNode As New Node
                        Manager.AddNode(clsNode)
                        clsNode.StartServer(clsNewClient)
                    Else
                        System.Threading.Thread.Sleep(100)
                    End If
                Catch ex As System.Threading.ThreadAbortException
                    Exit Do
                Catch ex As Exception
                    Framework.Misc.HandleException(ex)
                End Try
            Loop
        Catch ex As System.Threading.ThreadAbortException
            Return
        Catch ex As Exception
            Framework.Misc.HandleException(ex)
        End Try
    End Sub

End Class
